package org.dync.giftlibrary.widget;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;

import java.lang.reflect.Field;

/**
 * Created by KathLine on 2017/1/8.
 */
public class StrokeTextView extends Text implements Component.DrawTask {

    Paint m_TextPaint;
    int mInnerColor;
    int mOuterColor;
    private boolean m_bDrawSideLine = true; // 默认采用描边

    public StrokeTextView(Context context, int outerColor, int innnerColor) {
        super(context);
        m_TextPaint = new Paint();
        this.mInnerColor = innnerColor;
        this.mOuterColor = outerColor;
    }

    public StrokeTextView(Context context, AttrSet attrSet) {
        super(context, attrSet);
        m_TextPaint = new Paint();
        this.mInnerColor = getAttrSetInt(attrSet, "innnerColor", 0xffffff);
        this.mOuterColor = getAttrSetInt(attrSet, "outerColor", 0xffffff);

        addDrawTask(this);
    }

    public StrokeTextView(Context context, AttrSet attrSet, String styleName, int outerColor, int innnerColor) {
        super(context, attrSet, styleName);
        m_TextPaint = new Paint();
        this.mInnerColor = innnerColor;
        this.mOuterColor = outerColor;
        // TODO Auto-generated constructor stub
    }

    /**
     * 使用反射的方法进行字体颜色的设置
     *
     * @param color
     */
    private void setTextColorUseReflection(int color) {
        Field textColorField;
        try {
            textColorField = Text.class.getDeclaredField("mCurTextColor");
            textColorField.setAccessible(true);
            textColorField.set(this, color);
            textColorField.setAccessible(false);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        m_TextPaint.setColor(new Color(color));
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        if (m_bDrawSideLine) {
            // 描外层
            setTextColorUseReflection(mOuterColor);
            m_TextPaint.setStrokeWidth(5);
            m_TextPaint.setStyle(Paint.Style.FILLANDSTROKE_STYLE);

            // 描内层，恢复原先的画笔
            setTextColorUseReflection(mInnerColor);
            m_TextPaint.setStrokeWidth(0);
            m_TextPaint.setStyle(Paint.Style.FILLANDSTROKE_STYLE);
        }
    }

    public static int getAttrSetInt(AttrSet attrs, String key, int def) {
        if (attrs.getAttr(key).isPresent()) {
            return attrs.getAttr(key).get().getIntegerValue();
        } else {
            return def;
        }
    }
}
